﻿using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Abp.Application.Services.Dto;
using Abp.AspNetCore.Mvc.Authorization;
using Partner.Surround.Authorization;
using Partner.Surround.Controllers;
using Partner.Surround.Web.Models.Users;
using Partner.Surround.Notifications;
using Partner.Surround.Web.Models.Common;
using Partner.Surround.Notifications.Dto;
using Partner.Surround.Authorization.Users;
using Partner.Surround.Authorization.Users.Dto;
using Partner.Surround.Authorization.Roles;
using Partner.Surround.Organizations;
using Partner.Surround.Web.Models.Roles;
using System.Collections.Generic;
using Partner.Surround.Web.Models.OrganizationUnits;

namespace Partner.Surround.Web.Controllers
{
    /// <summary>
    /// 用户控制器
    /// </summary>
    [AbpMvcAuthorize]
    public class UsersController : SurroundControllerWebBase
    {
        #region 初始化
        private readonly IUserAppService _userAppService;
        private readonly IRoleAppService _roleAppService;
        private readonly IOrganizationUnitAppService _organizationUnitAppService;
        private readonly INotificationAppService _notificationAppService;

        public UsersController(
            IUserAppService userAppService,
            IRoleAppService roleAppService,
            IOrganizationUnitAppService organizationUnitAppService,
            INotificationAppService notificationAppService)
        {
            _userAppService = userAppService;
            _roleAppService = roleAppService;
            _organizationUnitAppService = organizationUnitAppService;
            _notificationAppService = notificationAppService;
        }
        #endregion

        #region 用户管理
        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 根据分页条件获取用户列表
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> GetUserList(GetPagedUserViewModel viewModel)
        {
            var input = PagedViewModelMapToPagedInputDto<GetPagedUserViewModel, GetPagedUserInput>(viewModel);
            var pagedUserList = await _userAppService.GetPagedUser(input);

            return Json(new PagedResultViewModel<UserListDto>(pagedUserList.TotalCount, pagedUserList.Items));
        }

        /// <summary>
        /// 创建或更新用户
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<ActionResult> CreateOrUpdateUser(UserRequestViewModel viewModel)
        {
            var userForEditOutput = await _userAppService.GetUserForEdit(new NullableIdDto<long>(viewModel.UserId));

            //用户信息
            var userViewModel = ObjectMapper.Map<UserEditViewModel>(userForEditOutput.User);

            //角色信息
            var roleListViewModel = ObjectMapper.Map<List<RoleListViewModel>>(userForEditOutput.RoleList);
            for (int i = 0; i < roleListViewModel.Count; i++)
            {
                roleListViewModel[i].IsAssigned = userForEditOutput.RoleNames.Contains(roleListViewModel[i].Name);
            }

            //组织机构信息
            var organizationUnitListViewModel = ObjectMapper.Map<List<OrganizationUnitListViewModel>>(userForEditOutput.OrganizationUnitList);
            for (int i = 0; i < organizationUnitListViewModel.Count; i++)
            {
                organizationUnitListViewModel[i].Checked = userForEditOutput.MemberedOrganizationUnitIds.Contains(organizationUnitListViewModel[i].Id);
            }

            var model = new UserFormViewModel
            {
                User = userViewModel,
                RoleList = roleListViewModel,
                OrganizationUnitList = organizationUnitListViewModel
            };

            return View(model);
        }

        /// <summary>
        /// 创建或更新用户
        /// </summary>
        /// <param name="createOrUpdateViewModel"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> CreateOrUpdateUser([FromBody]CreateOrUpdateUserInput input)
        {
            await _userAppService.CreateOrUpdateUser(input);

            return Json(new ResponseParamViewModel(input.User.Id.HasValue ? L("更新用户成功") : L("新增用户成功")));
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> DeleteUser([FromBody]List<EntityDto<long>> input)
        {
            await _userAppService.DeleteUser(input);

            return Json(new ResponseParamViewModel(L("删除用户成功")));
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> ResetUserPassword([FromBody]ResetPasswordInput input)
        {
            var success = await _userAppService.ResetPassword(input);
            var msg = success ? "密码重置成功" : "密码重置失败";
            return Json(new { success, msg });
        }
        #endregion

        #region 消息通知
        /// <summary>
        /// 通知设置
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> NotificationSetting()
        {
            var notificationSettings = await _notificationAppService.GetNotificationSettings();
            return View(notificationSettings);
        }

        /// <summary>
        /// 更新通知订阅
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UpdateNotificationSetting([FromBody]UpdateNotificationSettingsInput input)
        {
            await _notificationAppService.UpdateNotificationSettings(input);
            return Json(new ResponseParamViewModel("通知设置已更新"));
        }
        #endregion
    }
}
